package com.feiyun.erp.controller;


import com.feiyun.erp.entity.Functions;
import com.feiyun.erp.service.IFunctionsService;
import com.feiyun.erp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  权限菜单的前端控制器
 * </p>
 *
 * @author xray
 * @since 2021-05-03
 */
@RestController
@RequestMapping("/functions")
public class FunctionsController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IFunctionsService functionsService;

    /**
     * 根据用户名查询权限
     * @return
     */
    @GetMapping("/username")
    public ResponseEntity<List<Functions>> getSubFunctionsByUsername(){
        //获得Security中的用户名
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal != null && principal instanceof User) {
            User user = (User) principal;
            List<Functions> functions = userService.getFunctionsAndSubFunctionsByUsername(user.getUsername());
            return ResponseEntity.ok(functions);
        }
        return null;
    }

    /**
     * 查询所有权限
     * @return
     */
    @GetMapping
    public ResponseEntity<List<Functions>> getAllFunctions(){
        List<Functions> allFunctions = functionsService.getAllFunctions();
        return ResponseEntity.ok(allFunctions);
    }

    /**
     * 根据角色查询权限
     * @param roleId
     * @return
     */
    @GetMapping("/role/{roleId}")
    public ResponseEntity<List<Functions>> getFunctionsByRoleId(@PathVariable String roleId){
        List<Functions> functionsByRoleId = functionsService.getFunctionsByRoleId(roleId);
        return ResponseEntity.ok(functionsByRoleId);
    }
}
